package ru.nsu.fit.ask_joe.user_interface_manager.realization;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import ru.nsu.fit.ask_joe.MainManager;
import ru.nsu.fit.ask_joe.R;
import ru.nsu.fit.ask_joe.user_interface_manager.interfaces.IPanel;
import ru.nsu.fit.client.core.response.KernelResponse;
import ru.nsu.fit.client.core.response.UserStatisticsData;

public class ProfilePanel implements IPanel {

private static final int resourceId = R.layout.my_profile;
	
	private final View _view;
	private final Button _buttonMyQuest, _buttonOtherQuest;
	private final TextView _textTop, _textPoints;
    private ProgressDialog progressDialog;
    private UserStatisticsData statisticsData = null;
	
	public ProfilePanel()
	{
		_view = MainManager.getUserInterfaceManager().getMainActivity().getLayoutInflater().inflate(resourceId, null);
		
		_buttonMyQuest = (Button)_view.findViewById(R.id.button_my_quest);
		_buttonMyQuest.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				MainManager.getUserInterfaceManager().setCurrentPanel(new MyQuestionPanel());
			}
		});
		
		_buttonOtherQuest = (Button)_view.findViewById(R.id.button_other_quest);
		_buttonOtherQuest.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				MainManager.getUserInterfaceManager().setCurrentPanel(new OtherQuestionPanel());
			}
		});
		
		_textTop = (TextView)_view.findViewById(R.id.text_top);
		_textPoints = (TextView)_view.findViewById(R.id.text_points);
        MainManager.getUserInterfaceManager().setStatistics(null);
		//TODO Looks natural
        loadRating();
//		_textTop.setText("Place in Top: 2");
//		_textPoints.setText("With 6 points");
	}

    private void loadRating(){
        statisticsData = MainManager.getUserInterfaceManager().getStatistics();
        if(statisticsData == null){
            if(progressDialog == null){
                progressDialog = ProgressDialog.show(_view.getContext(), _view.getContext().getString(R.string.Message_PleaseWait), _view.getContext().getString(R.string.Message_LoadingRating));
            }
//            statisticsData = null;
            int responseId = MainManager.getClientKernel().getUserStatistics();
            new ResponseProccessor().execute(responseId);
        }
        else{
            if (progressDialog != null)
            {
                progressDialog.dismiss();
                progressDialog = null;
            }
            showStat();
        }
    }

    private void showStat(){
        if(statisticsData == null){
            return;
        }
        _textTop.setText("Place in Top: " + statisticsData.getUserRatingPosition());
		_textPoints.setText("With " + statisticsData.getUserRating() + " points");

    }

	@Override
	public View getView() {
		return _view;
	}

    private class ResponseProccessor extends AsyncTask<Integer, Void, KernelResponse>{
        @Override
        protected KernelResponse doInBackground(Integer... params) {
            KernelResponse response = null;
            try {
                //Waiting for response
                do
                {
                    response = MainManager.getClientKernel().getResponse(params[0]);
                    Thread.sleep(100);
                } while (response == null);
            }
            catch (InterruptedException e)
            {
                MainManager.getLogManager().getLogger().printError(e.getMessage());
            }
            return response;
        }

        @Override
        protected void onPostExecute(KernelResponse result) {
            super.onPostExecute(result);
            if(result.isSuccessful() && result.getData() != null){
                statisticsData = (UserStatisticsData) result.getData();
                MainManager.getUserInterfaceManager().setStatistics(statisticsData);
                loadRating();
            }
            else {
                if(progressDialog != null){
                    progressDialog.dismiss();
                    progressDialog = null;
                }
                AlertDialog.Builder builder =  new AlertDialog.Builder(getView().getContext());
                builder.setTitle(getView().getContext().getString(R.string.Message_Error));
                builder.setMessage(result.getErrorText()); //TODO translate error message into current language
                builder.setPositiveButton(getView().getContext().getString(R.string.Button_Ok), null);
                builder.show();
                MainManager.getLogManager().getLogger().printError("Cannot get my statistics. Result = " + result.getErrorText());
            }
        }
    }
}
